import grails.converters.JSON
import grails.util.JSonBuilder

class SearchController {

    def indexService

    def index = { }

    def explain = {
        def url = params.url
        def explains = []
        def entry
        if (url) {
            entry = Entry.findByLink(url)
        }
        if (entry) {
            explains = indexService.explainMoreLikeThis(entry)
        } else {
            explains = indexService.explainSearchFor(params.content, params.title, params.tags, params.code)
        }
        [explains: explains]
    }

    def mlt(url) { 
        def entries = []
        def entry
        if (url) {
            entry = Entry.findByLink(url)
        }
        if (entry) {
            entries = indexService.moreLikeThis(entry, params.code)
        } else {
            entries = indexService.searchFor(params.content, params.title, params.tags, params.code)
        }
        def out = new StringWriter()
        new JSonBuilder(out).json {
            data {
                  entries.each {
                      data(title:it.title, link:it.link)
                  }
            }        
        }
        return out.toString()
    }

    def json = {
        def url = params.url
        def json = mlt(url)
        render "${json}"
    }

    def jsonp = { 
        def url = params.url
        def json = mlt(url)
        render "${params.callback}(${json})"
    }

    def search = {
        def hits = indexService.search(params.str)
        def iterate = hits.iterator()
        def cnt = hits.length() 
        def result = []
        for (def i = 0; i < cnt; i++) {
            def doc = hits.doc(i)
            def id = doc.get('id')
            def entry = Entry.get(id)            
            result.add([id: id, score: hits.score(i), entry: entry])
        }
        [result: result]
    }
}
